package com.whut.www.file_storage.activity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.www.file_storage.CustomSQLiteOpenHelper;
import com.whut.www.file_storage.R;

public class CursorLoaderActivity extends AppCompatActivity implements LoaderManager
        .LoaderCallbacks<Cursor> {
    //数据库名
    private static final String DB_NAME = "db_words.db";
    //数据库版本
    private static final int DB_VERSION = 1;
    //loaderId
    private static final int LOADER_ID = 1;
    //表名
    private static final String tableName = "tb_words";
    //ContentProvider的查询路径
    private String uri_word = "content://com.palfund/tb_words";
    private SQLiteDatabase mSqLiteDatabase;
    private SimpleCursorAdapter mCursorAdapter;
    private LoaderManager mLoaderManager;
    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task_loader);
        //初始化View
        initView();
        //初始化SqLiteDatabase
        initDataBase();
        //初始化loader
        initLoader();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterForContextMenu(mListView);
        if (mLoaderManager != null) {
            //销毁loader
            Log.i("CursorLoaderActivity", "---onDestroy()--->");
            mLoaderManager.destroyLoader(LOADER_ID);
        }
        mSqLiteDatabase.close();
        mCursorAdapter.changeCursor(null);
    }


    private void initView() {
        mListView = (ListView) findViewById(R.id.listView);
        TextView textView = (TextView) findViewById(R.id.tv_empty);
        mListView.setEmptyView(textView);
        mCursorAdapter = new SimpleCursorAdapter(this, R.layout.item_listview, null, new
                String[]{"word", "detail"}, new int[]{R.id.tv_itemSummary, R.id.tv_itemDetail},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        mListView.setAdapter(mCursorAdapter);
        registerForContextMenu(mListView);
        Log.i("CursorLoaderActivity", "---initView()--->" + "");
    }

    private void initLoader() {
        mLoaderManager = getSupportLoaderManager();
        mLoaderManager.initLoader(LOADER_ID, null, this);
    }

    private void initDataBase() {
        //实例化SQLiteOpenHelper
        CustomSQLiteOpenHelper customSQLiteOpenHelper = new CustomSQLiteOpenHelper(this, DB_NAME,
                null, DB_VERSION);
        //获取sqLiteDatabase对象
        mSqLiteDatabase = customSQLiteOpenHelper.getReadableDatabase();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_cursor_loader, menu);
        //获取item
        MenuItem item = menu.findItem(R.id.action_search);
        //获取actionView
        SearchView searchView = (SearchView) item.getActionView();
        //searchView添加监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.i("CursorLoaderActivity", "---onQueryTextSubmit()--->" + "submit");
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.i("CursorLoaderActivity", "---onQueryTextChange()--->" + "change");
                Bundle bundle = new Bundle();
                bundle.putString("keyWord", newText);
                mLoaderManager.restartLoader(LOADER_ID, bundle, CursorLoaderActivity.this);
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_insert:
                actionInsert();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void actionInsert() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
        final EditText et_summary = (EditText) view.findViewById(R.id.et_summary);
        final EditText et_detail = (EditText) view.findViewById(R.id.et_detail);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_input_add).setTitle("添加").setView(view)
                .setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String summary = et_summary.getText().toString();
                String detail = et_detail.getText().toString();
                ContentValues contentValues = new ContentValues();
                contentValues.put("word", summary);
                contentValues.put("detail", detail);
                //返回值所在id
                long id = mSqLiteDatabase.insert(tableName, null, contentValues);
                if (id > 0) {
                    Log.i("MainActivity", "---id--->" + id);
                    //3种加载数据方式加载数据
                    //mCursorLoader.startLoading();
                    //会重新创建loader
                    //mLoaderManager.restartLoader(LOADER_ID, null, MainActivity.this);
                    //通知数据库数据改变,以便CursorLoader更新UI
                    getContentResolver().notifyChange(Uri.parse(uri_word), null);
                } else {
                    Toast.makeText(CursorLoaderActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
            }
        }).show();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo
            menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.context, menu);
        //ContextMenu添加HeaderIcon、HeaderTitle
        menu.setHeaderIcon(android.R.drawable.ic_menu_info_details).setHeaderTitle("which is " +
                "your" + " choice");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        //点击的item的poition
        int position = menuInfo.position;
        //点击的item在数据库中的id
        long id = menuInfo.id;
        Cursor cursor = (Cursor) mCursorAdapter.getItem(position);
        final String word = cursor.getString(cursor.getColumnIndex("word"));
        final String detail = cursor.getString(cursor.getColumnIndex("detail"));
        final int _id = cursor.getInt(cursor.getColumnIndex("_id"));
        Log.i("CursorLoaderActivity", "---onContextItemSelected()--->" + "position:" + position +
                "\t" + "id:" + id + "\t" + _id);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (item.getItemId()) {
            case R.id.action_delete:
                actionDelete(word, _id, builder);
                break;
            case R.id.action_update:
                actionUpdate(word, detail, _id, builder);

                break;

        }
        builder.show();
        return super.onContextItemSelected(item);
    }

    private void actionUpdate(String word, String detail, final int _id, AlertDialog.Builder
            builder) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
        final EditText et_summary = (EditText) view.findViewById(R.id.et_summary);
        final EditText et_detail = (EditText) view.findViewById(R.id.et_detail);
        et_detail.setText(detail);
        et_summary.setText(word);
        builder.setIcon(android.R.drawable.ic_menu_upload).setTitle("修改" + word).setMessage
                ("What" + " do you want to do").setView(view).setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newDetail = et_detail.getText().toString();
                String newWord = et_summary.getText().toString();
                ContentValues contentValues = new ContentValues();
                contentValues.put("word", newWord);
                contentValues.put("detail", newDetail);
                //更新的数量
                int updateCount = mSqLiteDatabase.update(tableName, contentValues, "_id=?", new
                        String[]{String.valueOf(_id)});
                if (updateCount > 0) {
                    //通知数据库数据改变,以便CursorLoader更新UI
                    getContentResolver().notifyChange(Uri.parse(uri_word), null);
                } else {
                    Toast.makeText(CursorLoaderActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void actionDelete(String word, final int _id, AlertDialog.Builder builder) {
        builder.setIcon(android.R.drawable.ic_delete).setTitle("删除" + word).setMessage("What do "
                + "you want to do").setNegativeButton("取消", null).setPositiveButton("确定", new
                DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //删除的条目的数量
                int deleteCount = mSqLiteDatabase.delete(tableName, "_id=?", new String[]{String
                        .valueOf(_id)});
                if (deleteCount > 0) {
                    //通知数据库数据改变,以便CursorLoader更新UI
                    getContentResolver().notifyChange(Uri.parse(uri_word), null);
                }else {
                    Toast.makeText(CursorLoaderActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////
    //LoaderManager.LoaderCallbacks<Cursor>
    ////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * @param id
     * @param args
     * @return
     */
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Log.i("CursorLoaderActivity", "---onCreateLoader()--->");
        if (args != null) {
            String keyWord = args.getString("keyWord");
            return new CursorLoader(this, Uri.parse(uri_word), null, "word like ?", new
                    String[]{"%" + keyWord + "%"}, null);
        }
        return new CursorLoader(this, Uri.parse(uri_word), new String[]{"_id", "word", "detail"},
                null, null, null);
    }

    /**
     * @param loader
     * @param data
     */
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        Log.i("CursorLoaderActivity", "---onLoadFinished()--->");
        mCursorAdapter.changeCursor(data);
    }

    /**
     * @param loader
     */
    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        Log.i("CursorLoaderActivity", "---onLoaderReset()--->");
        mCursorAdapter.changeCursor(null);
    }


}
